# -*- coding: UTF-8 -*-
# 2023/11/26 23:30
import os.path
from concurrent.futures import ThreadPoolExecutor
from threading import Thread

import requests
from retry import retry

from tools.get_configer import my_configer
from tools.get_icon import confirm
from tools.get_logger import get_logger
from tools.show_toast import show_toast

configer = my_configer()
loger = get_logger()


class pool_download_image:
    """
    在线程池进行下载,独立线程下载完后通知用户
    """

    def __init__(self, download_list: list):
        """
        批量下载任务
        :param download_list: 待下载图片列表以[[path, url]]形式传递所有需要下载列表
        """
        self.download_list = download_list

        download_pool_Thread = Thread(target=self.run)
        download_pool_Thread.start()

    def run(self):
        with ThreadPoolExecutor(max_workers=8) as download_pool:  # 创建一个最大容纳数量为max_workers的线程池
            for save_path, img_url in self.download_list:

                if not os.path.isfile(save_path):
                    task_future = download_pool.submit(self.download_img, img_url, save_path)
                    setattr(task_future, "save_path", save_path)
                    setattr(task_future, "img_url", img_url)

                    loger.info(f"提交下载任务,保存位置:{save_path}, 图片url:{img_url}")

                    # 给所有task_future添加完成回调任务
                    task_future.add_done_callback(self.future_call_back)

                else:
                    loger.info(f"检测到{save_path}已下载,或存在重名文件请确认")
                    show_toast(title="请确认", message=f"检测到{save_path}已下载,或存在重名文件请确认", icon_path=confirm, image=save_path)

            download_pool.shutdown(wait=True)
            show_toast(title="请确认", message=f"提交的所有下载任务已完成!!", icon_path=confirm)

    def future_call_back(self, task_future):
        save_path = getattr(task_future, "save_path")
        img_url = getattr(task_future, "img_url")
        try:
            task_future_result = task_future.result()

            # 如果返回None表示下载成功,更新对应按钮图片
            if task_future_result is None:
                loger.info(f"线程回调更新,下载成功, ,保存位置:{save_path}, 图片url:{img_url}")

        except:
            task_future_exception = task_future.exception()
            message = f"经过多次尝试,仍有future下载错误,报错信息为:{type(task_future_exception)},保存位置:{save_path}, 图片url:{img_url}"
            loger.error(message)
            show_toast(message=f"检测到{save_path}已下载,或存在重名文件请确认")

    @retry(tries=5)
    def download_img(self, url: str, save_path: str) -> None:
        """
        根据传入的图片地址,进行下载
        :param self:
        :param url: 图片url
        :param save_path: 保存路径
        :return:
        """

        r = requests.get(url, timeout=30)
        response = r.content

        with open(save_path, "wb") as f:
            f.write(response)

        r.close()

        loger.info(f"图片保存成功,保存位置:{save_path},图片url:{url}")
